

from fastapi import APIRouter

router=APIRouter(prefix='/item' )
from setting import mongo_db,response_model

item_collection=mongo_db['item']

from pydantic import BaseModel

class ItemModel(BaseModel):
    item_id: int = None  # 默认不需要写，数据库会自动生成  
    name: str
    price: float
    stock: int
# 添加商品
@router.post('/', summary='添加商品')
def add_item(item: ItemModel):
    """
    添加商品
    :param item: 商品信息
    :return: 商品详情
    """
    item_data=item.model_dump()
    item_data['item_id']=item_collection.count_documents({})+1
    res=item_collection.insert_one(item_data)
    response_model.code=200
    response_model.msg='add-item-success'
    response_model.data={"_id":str(res.inserted_id)}
    return response_model

# 根据id查询商品
@router.get('/{item_id}', summary='根据id查询商品')
def get_item(item_id: int):
    """
    根据id查询商品
    :param item_id: 商品id
    :return: 商品详情
    """
    res=item_collection.find_one({'item_id': item_id})
    res['_id']=str(res['_id'])
    response_model.code=200
    response_model.msg='get-item-success'
    response_model.data=res
    return response_model
